<template>
  <div>
    <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-collapse v-model="activeNames" accordion  v-loading="loading" :element-loading-text="loadingText">
        <el-collapse-item title="Hourse Status List" name="1"  style="padding-left: 15px;">
          <el-tag style="margin: 5px 5px;min-width:215px;"
                  v-for="(tag, index) in dataList"
                  closable
                  :type="(index+1 % 1 == 0) ? 'success' : (index % 2 == 0) ? 'info' : (index % 3 == 0) ? 'warning' : (index % 4 == 0) ? 'danger' : ''"
                  @click="clickTag(index)" @close="closeTag(tag.id)">
            NO:{{tag.id}}.[{{tag.startDate}} to {{tag.endDate}}]


          </el-tag>

        </el-collapse-item>
        <el-collapse-item title="Add Hourse Status" name="2" style="padding-left: 15px;">
          <el-form ref="formData" :model="formData"  :rules="rules" label-width="125px">
            <el-form-item label="Physical Room Id" class="form-item-wd" >
              <el-input
                placeholder="Physical Room Id"
                v-model="pid"
                :disabled="true">
              </el-input>
            </el-form-item>

            <el-form-item label="Logical Room Id"  prop="logical_room_id" class="form-item-wd">
              <el-select v-model="formData.logical_room_id" placeholder="Please Select A Logical Room Id">
                <el-option
                  v-for="item in logicRoomList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="Date Range"  prop="dateRange">
              <div class="block" style="width: 100%">
                <el-date-picker style="width: 70%"
                                v-model="formData.dateRange"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="to"
                                start-placeholder="Start Date"
                                end-placeholder="End Date"
                                :picker-options="pickerOptions"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd" @change="changeDateRange">
                </el-date-picker>
                <span>Total：{{totalDays}} Nights</span>
              </div>
            </el-form-item>


            <el-form-item label="Room State"  required>
              <el-switch
                v-model="formData.hourseStatus"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>

            <el-form-item label="Comment" class="form-item-wd" prop="comment">
              <el-input type="textarea" v-model="formData.comment"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doSave">Save Changes</el-button>
              <el-button  @click="doClose">Close</el-button>
              <el-button  @click="doReset">Add Data</el-button>
              <el-button type="danger" icon="el-icon-refresh" circle @click="doSynchro"></el-button>
            </el-form-item>
          </el-form>

        </el-collapse-item>
      </el-collapse>

    </el-scrollbar>


  </div>

</template>

<script>
    import {addModel,searchModel,get,updateModel,deleteModel,addModels,updateModels} from "@/api/model";
    import {getRoomEvents,insertOrder} from "@/api/event";
    import {submitAction} from "@/api/task";
    export default {
        name: "HourseStatusForm",
        props:["pid","listingId"],
        data() {
            return {
                model: 'ICalendar', //
                bodyHeight:900,
                parentObj : null, //父对象
                loading:false,
                loadingText:'data load ...',
                totalDays:0,
                id:null,    //当前选中的房态ID
                activeNames: ['1','2'],
                dataList : [],
                logicRoomList:[],
                formData: this.getInitFormData(),
                rules: this.getInitRules(),
                pickerOptions: {
                    shortcuts: [{
                        text: 'Last week',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: 'Last month',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: 'Last three months',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }],
                }
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
        },
        mounted(){

        },
        methods: {
            getInitFormData(){
                return  {
                    logical_room_id:null,
                    checkin:null,
                    checkout:null,
                    comment:null,
                    type:"2",
                    dateRange:null,
                    hourseStatus:false
                };
            },
            getInitRules() {
                const _this = this;
                const custRulesCfg = this.getCustRulesConfig();
                return {
                    logical_room_id:[
                        { required: true, message: 'Please Enter Logical_Room_Id', trigger: 'blur' },
                        { min: 1, max: 100, message: '1 to 100 characters in length', trigger: 'blur' }
                    ],
                    dateRange:[
                        { required: true, message: 'Please Select A Date range', trigger: 'change', type: 'array'}
                    ],
                    comment:[
                        { required: true, message: 'Please Enter Comment', trigger: 'blur' },
                        { min: 1, max: 1000, message: '1 to 1000 characters in length', trigger: 'blur' }
                    ],
                    // hourseStatus:[
                    //     { required: true, message: 'Please Select Room State', trigger: 'change' }
                    // ]
                };
            },
            getCustRulesConfig(){
                return {
                    intValid: function(label, min, max){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseInt(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an integer value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an integer value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    callback();
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }
                        };
                        return intValidFun;
                    },
                    floatValid: function(label, min, max,custCb){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseFloat(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an float value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an float value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    if(custCb){
                                        custCb(rule, value, callback);
                                    }else{
                                        callback();
                                    }
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }

                        };
                        return intValidFun;
                    },
                };
            },
            refresh(_parentObj){
                console.log("refresh to do ...");
                this.parentObj = _parentObj;
                this.loadDatas();
            },
          setLogicRoomList(_logicRoomList){
            this.logicRoomList = _logicRoomList;
          },
          changeDateRange(value){
              if(!value || value.length == 0){
                  this.totalDays = 0;
              }else{
                  const [startDate, endDate] = value;
                  this.totalDays = this.getDays(startDate, endDate);
              }
          },
            /**
             *  获取截止日期和起始日期之间的天数
             * */
            getDays(startDate, endDate){
                const days = moment(endDate).diff(moment(startDate), 'days')
                //console.log(endDate+" - "+startDate+ "="+ days);
                return days;
            },
            /**
             * 加载数据
             */
            loadDatas(){
                console.log("loadDatas to do ...");
                this.dataList = this.parentObj.selHourseStatusDatas;
                this.doReset();
            },
            /**
             * 保存数据
             */
            doSave(){
                console.log("doSave to do ...");
                const _this = this;
                console.log(this.formData);
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        this.formData.checkin = this.formData.dateRange[0];
                        this.formData.checkout = this.formData.dateRange[1];
                        const _hourseStatus = this.formData.hourseStatus;
                        if(!_this.id && _hourseStatus){ //当前日期范围的房源不需要打开房态
                            _this.$message.error('No room status needs to be opened for the current date range!');
                            return;
                        }
                        if(_hourseStatus){//如果打开状态就直接是删除房态数据即可
                            this.closeTag(_this.id);
                            return;
                        }
                        _this.loading = true;
                        if(_this.id){
                            deleteModel(this.model, _this.id).then(res => {
                               this.insertData(_formData);  //只有关闭状态才需要重新插入
                            }).catch(reason => {
                                _this.loading = false;
                                console.log("deleteModel Failure...");
                                console.error(reason);
                                //_this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }else{
                            this.insertData(_formData);
                        }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });
            },
            insertData(_formData){
                const _this = this;
                this.loading = true;
                delete _formData["dateRange"];
                delete _formData["hourseStatus"];
                insertOrder(_formData).then(res => {
                    this.loading = false;
                    _this.doSynchro();
                    _this.$message({
                        type: 'info',
                        message: 'Save Data Success!'
                    });
                   _this.reloadParentData();
                    console.log(res);
                }).catch(reason => {
                    _this.loading = false;
                    console.log(reason);
                });
            },
            reloadParentData(){
                const _this = this;
                this.doClose();
                _this.parentObj.loadOrderData((list) =>{
                    const _myHourseStatus = list.filter(item => {
                        return item.physical_room_id == _this.pid;
                    });
                    if(!_myHourseStatus || _myHourseStatus.length==0){
                        this.dataList = [];
                        return;
                    }
                    let _dataLiist = [];
                    _myHourseStatus.forEach(item => {
                        const _room_events = item.room_events;
                        if(!_room_events || _room_events.length == 0) return;
                        const _arr = _room_events.map(item => {
                            return {id:item.id,logical_room_id:item.logical_room_id,startDate:item.start, endDate:item.end,title:item.title};
                        });
                        _dataLiist = _dataLiist.concat(_arr);
                    });
                    this.dataList = _dataLiist;
                });
            },
            clickTag(index){
                const _this = this;
                const _data = this.dataList[index];
                console.log(_data);
                this.id = _data.id;
                const {startDate,endDate} = _data;
                console.log("startDate="+startDate);
                const _startDate = new Date(startDate.replace(/-/g, "\/"));
                const _endDate = new Date(endDate.replace(/-/g, "\/"));
                const _dateRange = [startDate,endDate];
                this.formData = {
                    logical_room_id: _data.logical_room_id,
                    checkin: startDate,
                    checkout: endDate,
                    comment: _data.title,
                    type:"2",
                    dateRange:_dateRange,
                    hourseStatus:false
                };
            },
            closeTag(_id){
                const _this = this;
                this.id = _id;
                this.loading = true;
                deleteModel(this.model, _this.id).then(res => {
                    this.loading = false;
                    _this.$message({
                        type: 'info',
                        message: 'Save Data Success!'
                    });
                    _this.reloadParentData();
                }).catch(reason => {
                    _this.loading = false;
                    console.log("deleteModel Failure...");
                    console.error(reason);
                    //_this.$message.error('Please Check Input Form Data Has Errors!');
                });
            },
            getParent(){
                return this.parentObj ||  this.$parent;
            },
            doClose(){
                const _parent = this.parentObj ||  this.$parent;
                console.log(_parent);
                _parent.closeDrawer();
            },
            /**
             * 重置表单
             */
            doReset(){
                this.formData = this.getInitFormData();
                this.logicRoomList = [];
                this.id = null;
                if(this.$refs['formData']) this.$refs['formData'].resetFields();
            },
            /**
             * ActionTask ABNB API 同步
             */
            doSynchro(){
                const _this = this;
                if(!this.listingId){
                    _this.$message.error('PhysicalRoomListing id is null,Please Check Data...!');
                    return;
                }
                const actionName = "sync_calendar_to_airbnb";
                this.loadingText = "Calling API: "+actionName+" ...";
                this.loading = true;

                submitAction("PhysicalRoomListing", this.listingId,actionName).then(res => {
                    this.loading = false;
                    _this.$notify({
                        title: 'Success',
                        message: 'ListingId:'+ this.listingId+' call API:'+actionName+' succeeded !',
                        type: 'success'
                    });

                }).catch(reason => {
                    _this.loading = false;
                    console.log("deleteModel Failure...");
                    console.error(reason);
                    _this.$notify.error({
                        title: 'Error',
                        message: 'API:'+actionName+'  call error !'
                    });
                    //_this.$message.error('Please Check Input Form Data Has Errors!');
                });
            }
        }
    }
</script>

<style scoped>
  .input-size{
    width: 85%;
  }
  .form-item-wd{
    margin-right: 20px;
  }
</style>

